import { _decorator, clamp, Component, director, EditBox, instantiate, Label, Node, Size, size, Sprite, SpriteFrame, UITransform, v2, v3, Vec2, Vec3 } from 'cc';
import { AnimalType, CustomEventType } from './GlobalEnum';
import { CldObj } from './CldObj';
import { GridMap } from './GridMap';
import { LanGan } from './LanGan';
const { ccclass, property } = _decorator;

@ccclass('CldLayer')
export class CldLayer extends Component {
    @property(SpriteFrame)
    animSfArr: SpriteFrame[] = [];

    @property(GridMap)
    gridMap: GridMap = null;

    @property(Node)
    cldObj: Node = null;

    animSfRecs: { [name: string]: SpriteFrame } = {};

    protected onLoad(): void {
        this.animSfArr.forEach(sf => {
            this.animSfRecs[sf.name] = sf;
        })
        this.iniAnimal();
    }

    protected onEnable(): void {
        this.initEditBox();
    }

    reset() {
        this.node.removeAllChildren();
    }

    //#region ---按钮
    @property(EditBox)
    lvEdit: EditBox = null;
    @property(EditBox)
    sizeEidt: EditBox = null;

    curSizeWidth = 4;

    initEditBox() {
        this.curSizeWidth = this.gridMap.bigGridSize.width;
        this.sizeEidt.string = this.curSizeWidth.toString();
    }

    resetClick() {
        this.gridMap.node.active = false;
        // 
        this.curSizeWidth = parseInt(this.sizeEidt.string) || 2;
        this.gridMap.bigGridSize.set(this.curSizeWidth, this.curSizeWidth);
        this.gridMap.node.active = true;
        this.reset();
    }

    onSizeEidtEnd(e){
        let w = parseInt(this.sizeEidt.string) || 2;
        w = clamp(w, 2, 7);
        this.sizeEidt.string = w.toString();
    }

    saveClick() {
        const lv = parseInt(this.lvEdit.string) || 1;
        const lvData = this.getLvData(lv);
        console.log('----关卡数据', lvData);

        const data = { [lv]: lvData };
        downloadTxtFile('LvData' + lv, JSON.stringify(data));
    }

    //#endregion


    //#region ---创建动物
    @property(Sprite)
    displayAnim: Sprite = null;
    @property(Label)
    animIdxLabel: Label = null;

    curIdx = 0;

    iniAnimal() {
        this.animIdxLabel.string = this.curIdx.toString();
        this.displayAnim.spriteFrame = this.animSfArr[this.curIdx];
    }

    preAnimClick() {
        this.curIdx--;
        if (this.curIdx < 0) {
            this.curIdx = this.animSfArr.length - 1;
        }
        this.displayAnim.spriteFrame = this.animSfArr[this.curIdx];
        this.animIdxLabel.string = this.curIdx.toString();
    }
    nextAnimClick() {
        this.curIdx++;
        if (this.curIdx >= this.animSfArr.length) {
            this.curIdx = 0;
        }
        this.displayAnim.spriteFrame = this.animSfArr[this.curIdx];
        this.animIdxLabel.string = this.curIdx.toString();
    }

    createCld() {
        const node = instantiate(this.cldObj);
        node.parent = this.node;
        const wpos = v3(this.displayAnim.node.worldPosition);
        wpos.y += 50;
        node.setWorldPosition(wpos);

        const _size = size(
            this.gridMap.smallGridWidth * 4,
            this.gridMap.smallGridWidth * 2);
        node.getComponent(UITransform).setContentSize(_size);

        const _name = this.animSfArr[this.curIdx].name;
        node.getComponent(CldObj).init(_name as AnimalType, this.animSfRecs[_name]);
        node.active = true;
    }
    //#endregion

    //#region ---创建障碍物
    @property(Node)
    lanGan: Node = null;
    @property(Node)
    lanGanBtn: Node = null;
    createLanGan() {
        const node = instantiate(this.lanGan);
        node.parent = this.node;
        const wpos = v3(this.lanGanBtn.worldPosition);
        wpos.y += 100;
        node.setWorldPosition(wpos);

        const _size = size(
            this.gridMap.smallGridWidth * 2,
            this.gridMap.smallGridWidth * 1);
        node.getComponent(UITransform).setContentSize(_size);
        node.active = true;
    }

    //#endregion


    //#region ---获取关卡数据

    // 计算出所有物体相对网格位置 : 左上角为原点 -> 右下角
    getLvData(lv) {
        // 朝向
        const direcArr = {
            0: v2(1, 0),
            90: v2(0, 1),
            180: v2(-1, 0),
            270: v2(0, -1)
        }

        let data = new LvData();
        data.lv = lv;

        data.mapSize.set(this.gridMap.bigGridSize.width * 2,
            this.gridMap.bigGridSize.height * 2);
        data.gridSize.set(this.gridMap.smallGrigSize);
        // 左上角为原点
        const offset = v2(-data.mapSize.width * 0.5, -data.mapSize.height * 0.5);

        for (let i = 0; i < this.node.children.length; i++) {
            const node = this.node.children[i];

            const d = {
                name: null,
                angle: node.angle % 360,
                formatSize: size(),
                formatPos: v2(),
                direc: v2(direcArr[node.angle % 360])
            }
            const trans = node.getComponent(UITransform);
            d.formatSize.width = Math.floor(trans.width / this.gridMap.smallGridWidth) * 0.5;
            d.formatSize.height = Math.floor(trans.height / this.gridMap.smallGridWidth) * 0.5;
            //

            const cldObj = node.getComponent(CldObj);
            if (!cldObj) {
                // 围栏
                const obj = node.getComponent(LanGan);
                d.formatPos.set(obj.tarWpos.x + obj.curOffset.x,
                    obj.tarWpos.y + obj.curOffset.y);
                this.gridMap.floorPos(d.formatPos);
                d.name = 'fence';
                if (d.angle == 90 || d.angle == 270) {
                    // 垂直
                    d.formatPos.x += 0.5;
                } else {
                    // 水平
                    d.formatPos.y += 0.5;
                }
                // 转化成中心点为原点的坐标系坐标
                d.formatPos.multiplyScalar(0.5).add(offset);

                data.cldArr.push(d);
            } else {
                d.name = cldObj.curType;
                d.formatPos = v2(cldObj.tarWpos.x, cldObj.tarWpos.y);
                this.gridMap.floorPos(d.formatPos);
                d.formatPos.multiplyScalar(0.5).add(offset);

                data.animArr.push(d);
            }
        }
        // 加上周边围栏宽度  
        data.mapSize.width += 1;
        data.mapSize.height += 1;

        return data;
    }

    //#endregion
}

export class LvData {
    lv: number = 1;
    gridSize: Size = size();
    mapSize: Size = size();
    animArr: { name: string, angle: number, formatSize: Size, formatPos: Vec2, direc: Vec2 }[] = [];
    cldArr: { name: string, angle: number, formatSize: Size, formatPos: Vec2, direc: Vec2 }[] = [];
}


// 下载文件
function downloadTxtFile(name: string, str: string) {
    const content = str;
    const blob = new Blob([content], { type: 'text/plain' });
    const url = URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    link.download = name + '.txt';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    URL.revokeObjectURL(url);
}